package com.fg.cloud.factory.controller.agency;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.construction.ResultMap;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.AgencyEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyVo;
import com.fg.cloud.manager.entry.factory.FactoryUserEntity;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.entry.order.vo.OrderReturnVo;
import com.fg.cloud.manager.service.agency.AgencyService;

/**
 * 经销商用户controller
 * @author around
 * @date 2017-6-14
 */
@Controller
@RequestMapping("/agency")
public class AgencyController extends BaseController {

	@Autowired
	private AgencyService agencyService;
	
	/**
	 * 经销商详情页信息封装查询
	 * @param request
	 * @param session
	 * @param agency
	 * @return String 
	 */
	@RequestMapping(value = "/detail", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void detail(HttpServletRequest request, HttpServletResponse response, 
			AgencyEntity agency) {
		if (null == agency.getId()) {
			doResult(response, false, StatusCode.FINDERROR, null, "缺少经销商ID");
			return;
		}
		try {
			agency = agencyService.find(agency.getId());
			if(null == agency)
				doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_NULL);
			else
				doResult(response, true, StatusCode.FINDSUCCESS, agency, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
			e.printStackTrace();
		}
	}
	
	/**
	 * 分页查询
	 * @param request
	 * @param session
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param agency
	 */
	@RequestMapping(value = "/findList", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, 
			Integer page, Integer rows, String sort, String order,
			AgencyVo agency, String filterText, String areaNumber) {
		try {
			PageUtils<AgencyVo> pageinfo = new PageUtils<AgencyVo>(page, rows, sort, order); 
			Map<String, Object> condition = pageinfo.getCondition();
			
			condition.put("facId", getCurrentFactoryUser().getFacId());
			//过滤经销商名称/编码/联系人
			condition.put("filterText", filterText);
			condition.put("levelId", agency.getLevelId());
			/*if (null != agency.getAreaId()) {
				condition.put("areaId", agency.getAreaId());
				condition.put("areaNumber", areaNumber+"_"+agency.getAreaId());
			}*/
			
			//处理前端区域选择问题
			if (StringUtils.isNotEmpty(agency.getAreaNumberSort())) {
				String[] idArray = agency.getAreaNumberSort().split(",");
				condition.put("areaId", Long.valueOf(idArray[idArray.length-1]));
				condition.put("areaNumber", "0_"+agency.getAreaNumberSort().replace(",", "_"));
			}
			//状态
			if (null != agency.getStatus() && -1 != agency.getStatus()) 
				condition.put("status", agency.getStatus());
			
			pageinfo.setCondition(condition);
			agencyService.findList(pageinfo);
			doResult(response,true,StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response,false,StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:查询经销商信息封装为Select控件
	 * @param request
	 * @param response
	 * @param filter 过滤字段，可过滤number、name
	 * @author around
	 * @date 2017年8月3日上午9:40:46
	 */
	@RequestMapping(value = "/select", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void select(HttpServletRequest request, HttpServletResponse response, 
			String filter, AgencyVo agency) {
		try {
			agency.setFacId(getCurrentFactoryUser().getFacId());
			doResult(response, true, StatusCode.FINDSUCCESS, 
					agencyService.findBySelect(agency, filter), ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response, false, StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据厂商ID查询下属经销商
	 * @param request
	 * @param response
	 * @param filterText 过滤，参与编码，名称
	 */
	@RequestMapping(value = "/findListByFactory", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findListByFactory(HttpServletRequest request, HttpServletResponse response,
			String filterText) {
		FactoryUserEntity user = getCurrentFactoryUser();
		List<AgencyVo> agencyList = agencyService.findListByFactory(user.getId());
		if(agencyList.size() > 0)
			doResult(response, true, agencyList, "");
		else
			doResult(response, false, null, "未查询到数据!");
	}

	/**
	 * 新增/保存厂商用户信息
	 * @param request
	 * @param response
	 * @param agency AgencyEntity
	 */
	@RequestMapping(value = "/saveOrUpdate", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void saveOrUpdate(HttpServletRequest request, HttpServletResponse response, 
			String data) {
		try {
			if (null == data) {
				doResult(response, false, StatusCode.SAVEERROR, null, "待保存数据为空");
				return;
			}
			AgencyVo agency = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), AgencyVo.class);
			
			//处理前端特殊省市区问题
			if(StringUtils.isNotEmpty(agency.getAdministrative())) {
				if (agency.getAdministrative().length() > 3) {
					List<ResultMap> array = JSON.parseArray(agency.getAdministrative(), 
							ResultMap.class);
					agency.setProvince(array.get(0).getLabel());
					agency.setCity(array.get(1).getLabel());
					agency.setArea(array.get(2).getLabel());
				}
			}
			agency.setAdministrative(agency.getAdministrative().trim().toString());
			
			//处理前端区域选择问题
			if (StringUtils.isNotEmpty(agency.getAreaNumberSort())) {
				String[] idArray = agency.getAreaNumberSort().split(",");
				agency.setAreaId(Long.valueOf(idArray[idArray.length-1]));
				/*agency.setAreaNumber("0_"+agency.getAreaNumberSort().replace(",", "_")
						.substring(0, agency.getAreaNumberSort().lastIndexOf(",")));*/
			}
			
			boolean flag = agencyService.verifyUniquely(agency.getId(), 
					getCurrentFactoryUser().getFacId(), "ageName", agency.getAgeName());
			if (!flag) {
				doResult(response, false, StatusCode.SAVEERROR, null, "重复的经销商名称");
				return;
			}
			flag = agencyService.verifyUniquely(agency.getId(), 
					getCurrentFactoryUser().getFacId(), "ageNumber", agency.getAgeNumber());
			if (!flag) {
				doResult(response, false, StatusCode.SAVEERROR, null, "重复的经销商编码");
				return;
			}
			
			
			boolean flag1 = false;
			setUpdateInfo(agency, request);
			//id为空新增、不为空保存
			if(LongUtils.isEmpty(agency.getId())) {
				setCreateInfo(agency, request);
				agency.setFacId(getCurrentFactoryUser().getFacId());
				flag = agencyService.insertSelective(agency);
			} else {
				flag = agencyService.updateByPrimaryKeySelective(agency);
				//if(StringUtils.isNotEmpty(imgs)) flag1=agencyService.insertImgs(imgs, agency.getId());
			}
			
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS:StatusCode.SAVEERROR, 
					null, flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.SAVEERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除信息
	 * @param request
	 * @param response
	 * @param params AgencyEntity
	 * @throws IOException 
	 */
	@RequestMapping(value = "/deletes", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void deletes(HttpServletRequest request, HttpServletResponse response, 
			String ids) throws IOException {
		try {
			boolean flag = false;
			flag = agencyService.deletes(getCurrentFactoryUser().getId(),
					getCurrentFactoryUser().getFacId(),
					LongUtils.convert(ids.split("[, ]+")));
			doResult(response, flag, flag ? StatusCode.REMOVESUCCESS:StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 删除信息
	 * @param request
	 * @param response
	 * @param params AgencyEntity
	 * @throws IOException 
	 */
	@RequestMapping(value = "/deleteImg", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void deleteImage(HttpServletRequest request, HttpServletResponse response, 
			Long ageId, String url) throws IOException {
		try {
			boolean flag = agencyService.deleteImgs(ageId, url);
			doResult(response, flag, flag ? StatusCode.REMOVESUCCESS:StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
			e.printStackTrace();
		}
	}
	
	
}
